package com.xinenhua.businessserver.personal;

import android.app.Dialog;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.oasis.oasislib.base.BaseFragment;
import com.oasis.oasislib.base.HttpCallBack;
import com.oasis.oasislib.utils.DialogUtils;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.oasis.oasislib.view.CircleImageView;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.MainActivity;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.bill.PayBill;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.login.pojo.User;
import com.xinenhua.businessserver.personal.customer.AllCustomer;
import com.xinenhua.businessserver.personal.finance.ConfirmFinanceList;
import com.xinenhua.businessserver.personal.order.MyOrder;
import com.xinenhua.businessserver.personal.subscribe.PersonalSubscribe;
import com.xinenhua.businessserver.u.HttpRequest;
import com.xinenhua.businessserver.u.HttpResultPojo;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;


import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import id.zelory.compressor.Compressor;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.RequestBody;
import okhttp3.Response;
import q.rorbin.badgeview.QBadgeView;

/**
 * 个人中心！！！
 */
@ContentView(R.layout.personal)
public class PersonalFragment extends BaseFragment<MainActivity> {

    @ViewInject(R.id.father)
    LinearLayout father;

    @ViewInject(R.id.warpper_jiaofei)
    RelativeLayout warpper_jiaofei;

    //个人资料
    @ViewInject(R.id.personinfo)
    RelativeLayout personinfo;

    //我的签约
    @ViewInject(R.id.myorder)
    RelativeLayout myorder;

    //设置
    @ViewInject(R.id.imageView4)
    ImageView setting ;

    //注册用户
    @ViewInject(R.id.allCustomer)
    RelativeLayout allCustomer;

    //客户资料
    @ViewInject(R.id.custominfo)
    RelativeLayout custominfo;

    //待缴账单
    @ViewInject(R.id.paybill)
    RelativeLayout paybill;

    //客户预约
    @ViewInject(R.id.subscribe)
    RelativeLayout subscribe;

    //到账确认
    @ViewInject(R.id.financeConfirm)
    RelativeLayout financeConfirm;

    User user;

    //权限值  success  error

    //显示头像
    @ViewInject(R.id.circleImageView)
    CircleImageView circleImageView;

    @ViewInject(R.id.textView6)
    TextView nickname ;

    @ViewInject(R.id.textView9)
    TextView position ;

    private static final String  noPermission = "无相应权限 请联系管理员";

    @Override
    public void onStart() {
        super.onStart();
        user = Const.getUser() ;
        if(user!=null){
            LogUtil.e(TAG,user.toString());
        }else {
            LogUtil.e(TAG,"user null");
        }

        //初始化信息
        ImageLoader.getInstance().displayImage(user.getImageurl(),circleImageView);
        nickname.setText(user.getNickname());
        position.setText(user.getPosition());
    }

    @Override
    protected void start() {
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));

        //这行代码 可以设置红色提示小气泡
        //new QBadgeView(getActivity()).bindTarget(warpper_jiaofei).setBadgeNumber(20).setBadgeGravity(Gravity.END | Gravity.TOP).setBadgeTextSize(6,true);
        //个人资料
        personinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getGerenziliao())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),PersonInfo.class);
            }
        });
        //我的签约
        myorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getWodeqianyue())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),MyOrder.class);
            }
        });
        //设置
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ActivityUtils.startActivity(getActivity(),Setting.class);
            }
        });

        //注册用户
        allCustomer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getZhuceyonghu())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),AllCustomer.class);
            }
        });

        //客户资料
        custominfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getKehuziliao())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),CustomerInfo.class);
            }
        });

        //待缴账单
        paybill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getDaijiaozhangdan())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),PayBill.class);
            }
        });

        //客户预约
        subscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getKehuyuyue())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),PersonalSubscribe.class);
            }
        });

        //到账确认
        financeConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user==null||!"success".equals(user.getPurview().getDaozhangqueren())){
                    ToastUtils.shortToast(getActivity(),noPermission);
                    return;
                }
                ActivityUtils.startActivity(getActivity(),ConfirmFinanceList.class);
            }
        });

        //去上传头像
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AndPermission.with(PersonalFragment.this)
                        .permission(Permission.Group.STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                // TODO what to do.
                                LogUtil.e(TAG,"有读取手机权限");

                                MultiImageSelector.create(getActivity())
                                        .showCamera(true) // 是否显示相机. 默认为显示
                                        .single() // 单选模式
                                        .start(PersonalFragment.this, REQUEST_IMAGE);
                            }
                        }).onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        // TODO what to do
                        LogUtil.e(TAG,"无读取手机权限");
                        com.blankj.utilcode.util.ToastUtils.showLong("无读取文件权限 请去授权");
                    }
                }).start();
            }
        });

    }

    private static final int REQUEST_IMAGE = 99;

    Dialog dialog;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e(TAG,"onActivityResult requestCode "+requestCode +" resultCode "+ resultCode );
        //   选择图片 成功  onActivityResult requestCode 99 resultCode -1
        //选择图片 失败 onActivityResult requestCode 99 resultCode 0
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == -1){

                dialog = DialogUtils.createLoadingDialog(getActivity());
                dialog.show();
                // Get the result list of select image paths
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                // do your logic ....
                LogUtil.e(TAG,"onActivityResult  image path"+ path.get(0));
                try {
                    File compressedImageFile = new Compressor(getActivity()).compressToFile(new File(path.get(0)));

                    RequestParams requestParams = new RequestParams(Const.adminupdateImg);
                    requestParams.addBodyParameter("access_token",Const.access_token());
                    requestParams.addBodyParameter("admin_id",user.getAdmin_id()+"");
                    requestParams.addBodyParameter("image",compressedImageFile);

                    loadData(requestParams, new HttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                            LogUtil.e(TAG,"MultiImageSelectorActivity------"+result);
                            HttpResultPojo httpResultPojo = HttpRequest.dealHttpResult(result) ;
                            if(httpResultPojo.getCode()==0){
                                //显示提示信息
                                showMsg(httpResultPojo.getMsg());

                                String s = BaseHttp.getJsonDataAsString(result);
                                Gson gson = new Gson();
                                Type listType = new TypeToken<User>(){}.getType();
                                //得到了用户信息
                                User user = gson.fromJson(s, listType);

                                //存储用户信息
                                SPUtils spUtils = SPUtils.getInstance();
                                spUtils.put("user",s);

                                //刷新头像
                                ImageLoader.getInstance().displayImage(user.getImageurl(),circleImageView);
                            }else {
                                showMsg(httpResultPojo.getMsg());
                            }
                        }

                        @Override
                        public void onFinished() {
                            dialog.dismiss();
                        }

                        @Override
                        public void onCancelled(org.xutils.common.Callback.CancelledException cex) {

                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            LogUtil.e(TAG,"onerror"+ex.getMessage());
                            ex.printStackTrace();
                            showMsg("上传图片发生错误");
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    ToastUtils.shortToast(getActivity(),"发生错误 请重试");
                }
            }
        }


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.e(TAG,"onHiddenChanged  PersonalFragment   我的    "+  String.valueOf(hidden));
        if(hidden){
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));
        }else {
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));
        }

    }
}
